<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2025/5/6
  Time: 16:03
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <title>宿舍房间管理系统</title>
    <style>
        .pagination {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 12px;
            margin-top: 20px;
        }
        .btn-prev, .btn-next {
            padding: 6px 12px;
            border: 1px solid #d9d9d9;
            border-radius: 4px;
            background: #fff;
            cursor: pointer;
            font-size: 13px;
            transition: all 0.3s;
        }
        .btn-prev:hover, .btn-next:hover {
            color: #1890ff;
            border-color: #1890ff;
        }
        .btn-prev:disabled, .btn-next:disabled {
            color: #d9d9d9;
            border-color: #d9d9d9;
            cursor: not-allowed;
        }
        #pageInfo {
            min-width: 60px;
            text-align: center;
        }
        .table-striped tbody tr:nth-of-type(odd) {
            background-color: #f9f9f9;
        }

        .table-striped tbody tr.highlight {
            background-color: #e0e0e0;
        }

        .table td.text-center {
            text-align: center;
        }


        /* 新增模态框样式 */
        .modal-content {
            padding: 20px;
        }

        .modal-backdrop {
            display: none !important;
        }
    </style>
</head>
<body>
<div class="container">
    <!-- 搜索和操作栏 -->
    <div class="bg-light p-3 mb-3">
        <div class="d-flex justify-content-between align-items-center">
            <div class="me-3">宿舍房间管理</div>
            <div class="d-flex align-items-center">
                <input type="text" placeholder="房间ID" class="form-control me-2" id="roomNumber" style="width: 200px;">
                <button class="btn btn-success me-2" onclick="show()">查询</button>
                <button class="btn btn-primary me-2" id="addBtn" data-bs-toggle="modal"  data-bs-target="#addModal">新增</button>
                <button class="btn btn-secondary me-2" onclick="exportToExcel()">导出</button>
            </div>
        </div>
    </div>

    <!-- 新增宿舍房间模态框 -->
    <div class="modal fade" id="addModal" tabindex="-1" aria-labelledby="addModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="addModalLabel">新增宿舍房间</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form>
                        <div class="mb-3">
                            <label  class="form-label">所属楼栋</label>
                            <input type="text" class="form-control" id="addBuildingId" name="addBuildingId"
                                   maxlength="20" required>
                        </div>
                        <div class="mb-3">
                            <label for="addRoomNumber" class="form-label">房间编号</label>
                            <input type="text" class="form-control" id="addRoomNumber" name="roomNumber"
                                   maxlength="20" required>
                        </div>
                        <div class="mb-3">
                            <label for="addFloor" class="form-label">所在楼层</label>
                            <input type="number" class="form-control" id="addFloor" name="floor"
                                   min="1" required>
                        </div>
                        <div class="mb-3">
                            <label for="addCapacity" class="form-label">标准床位容量</label>
                            <select id="addCapacity" class="form-control" required>
                                <option value="2">2人间</option>
                                <option value="3">3人间</option>
                                <option value="4" selected>4人间</option>
                                <option value="5">5人间</option>
                                <option value="6">6人间</option>
                                <option value="7">7人间</option>
                                <option value="8">8人间</option>
                            </select>
                        </div>

                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                            <button type="button" class="btn btn-primary" id="confirmAdd">确认添加</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- 修改宿舍房间模态框 -->
    <div class="modal fade" id="editModal" tabindex="-1" aria-labelledby="editModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="editModalLabel">修改宿舍房间信息</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form>
                        <input type="hidden" id="editRoomId" name="roomId">
                        <div class="mb-3">
                            <label for="editBuildingId" class="form-label">所属楼栋</label>
                            <input type="text" id="editBuildingId" class="form-control" name="buildingid"maxlength="50" required>
                            <!-- 这里会通过JavaScript动态填充楼栋选项 -->
                        </div>
                        <div class="mb-3">
                            <label for="editRoomNumber" class="form-label">房间编号</label>
                            <input type="text" class="form-control" id="editRoomNumber" name="roomNumber"
                                   maxlength="20" required>
                        </div>
                        <div class="mb-3">
                            <label for="editFloor" class="form-label">所在楼层</label>
                            <input type="number" class="form-control" id="editFloor" name="floor"
                                   min="1" required>
                        </div>
                        <div class="mb-3">
                            <label for="editCapacity" class="form-label">标准床位容量</label>
                            <select id="editCapacity" class="form-control" required>
                                <option value="2">2人间</option>
                                <option value="3">3人间</option>
                                <option value="4">4人间</option>
                                <option value="5">5人间</option>
                                <option value="6">6人间</option>
                                <option value="7">7人间</option>
                                <option value="8">8人间</option>
                            </select>
                        </div>

                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                            <button type="button" class="btn btn-primary" id="confirmEdit">确认修改</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- 宿舍房间信息表格 -->
    <table class="table table-striped table-bordered" id="tableId">
        <thead>
        <tr>
            <th>房间ID</th>
            <th>所属楼栋</th>
            <th>房间编号</th>
            <th>所在楼层</th>
            <th>标准床位容量</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody>

        </tbody>
        <tfoot>
        <tr>
            <td colspan="6"> <div class="pagination">
                <button class="btn-prev" onclick="page(1)">上一页</button>
                <span id="pageInfo">第 1 页</span>
                <button class="btn-next" onclick="page(2)">下一页</button>
            </div></td>
        </tr>
        </tfoot>
    </table>
</div>

<input type="hidden" id="pages" >
<!-- 引入必要的JS库 -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>


<!--分页-->
<script>
    let currentPage = 0;
    let totalPages = 1;

    // 页面加载时初始化
    $(document).ready(function() {
        // loadBuildings();
        show();
    });

    <%--// 加载楼栋下拉框选项--%>
    <%--function loadBuildings() {--%>
    <%--    $.ajax({--%>
    <%--        url: '<%=request.getContextPath()%>/DormroomsController?op=cxb',--%>
    <%--        type: 'GET',--%>
    <%--        dataType: 'json',--%>
    <%--        success: function(response) {--%>
    <%--            try {--%>
    <%--                // 修改响应数据检查方式--%>
    <%--                if (!response || !response.list) {--%>
    <%--                    throw new Error('返回数据格式不正确');--%>
    <%--                }--%>

    <%--                // 直接使用response，因为dataType: 'json'已经自动解析--%>
    <%--                const buildings = response;--%>

    <%--                // 填充搜索框的楼栋下拉框--%>
    <%--                let options = '<option value="">所有楼栋</option>';--%>
    <%--                buildings.list.forEach(building => {--%>
    <%--                    options += '<option value="' + building.building_id + '">' + building.buildingname + '</option>';--%>
    <%--                });--%>
    <%--                $('#buildingId').html(options);--%>

    <%--                // 填充新增和修改模态框的楼栋下拉框--%>
    <%--                options = '<option value="">请选择楼栋</option>';--%>
    <%--                buildings.list.forEach(building => {--%>
    <%--                    options += '<option value="'+building.building_id+'">'+building.buildingname+'</option>';--%>
    <%--                });--%>
    <%--                $('#addBuildingId').html(options);--%>
    <%--                $('#editBuildingId').html(options);--%>
    <%--            } catch (e) {--%>
    <%--                console.error("解析楼栋数据错误:", e);--%>
    <%--                alert('加载楼栋信息失败: ' + e.message);--%>
    <%--            }--%>
    <%--        },--%>
    <%--        error: function() {--%>
    <%--            alert('请求失败，请检查网络连接');--%>
    <%--        }--%>
    <%--    });--%>
    <%--}--%>

    // 统一查询和分页功能
    function show(pageNum) {
        const roomNumber = $('#roomNumber').val();
        const buildingId = $('#buildingId').val();

        $.ajax({
            url: '<%=request.getContextPath()%>/DormroomsController?op=cxb',
            type: 'GET',
            data: {
                roomNumber: roomNumber,
                buildingId: buildingId,
                page: pageNum || currentPage,
                lid:roomNumber
            },
            success: function(response) {
                try {
                    const data = JSON.parse(response);
                    renderTable(data.list);
                    $("#pages").val(data.page);
                    updatePagination(data.page, data.totalPages);
                } catch (e) {
                    console.error('数据解析错误:', e);
                    alert('数据加载失败，请稍后重试');
                }
            },
            error: function() {
                alert('请求失败，请检查网络连接');
            }
        });
    }

    // 渲染表格数据
    function renderTable(data) {
        const tbody = $('#tableId tbody');
        let row="";
        tbody.empty();

        $.each(data, function(index, room) {
            row += '<tr>'+
                '<td>'+room.room_id+'</td>'+
                '<td>'+room.building_id+'</td>'+
                '<td>'+room.room_number+'</td>'+
                '<td>'+room.floor+'</td>'+
                '<td>'+room.capacity+'人间</td>'+
                '<td class="text-center">'+
                    '<button class="btn btn-warning me-1 edit-btn" data-id="'+room.room_id+'" data-building-id="'+room.building_id+'" data-number="'+room.room_number+'" data-floor="'+room.floor+'" data-capacity="'+room.capacity+'">修改</button>'+
                '<button class="btn btn-danger" onclick="sc('+room.room_id+',this)">删除</button>'+
                '</td>'+
                '</tr>';
        });

        tbody.append(row);
    }

    // 更新分页状态
    function updatePagination(currentPage, totalPages) {
        $('#pageInfo').text("第"+(currentPage+1)+"页");
        $('.btn-prev').prop('disabled', currentPage === 0);
        $('.btn-next').prop('disabled', currentPage >= totalPages - 1);

        // // 保存当前页和总页数
        // currentPage = currentPage;
        // totalPages = totalPages;
    }

    // 分页按钮点击事件
    function page(newPage) {
        let page = parseInt($("#pages").val());
        if(newPage === 1) {
            page--;
        } else {
            page++;
        }
        currentPage = page;
        show(currentPage);
    }

    // 删除宿舍房间函数
    function sc(id, that) {
        if (confirm("确定要删除房间ID为 " + id + " 的宿舍房间吗？")) {
            $.post("<%=request.getContextPath()%>/DormroomsController", {
                op: "scb",
                id: id
            }, function () {
                alert("删除成功");
                that.parentNode.parentNode.remove();
            }).fail(function () {
                alert("删除失败");
            });
        }
    }

    // 新增宿舍房间功能
    $(document).ready(function () {
        // 确认添加按钮点击事件
        $("#confirmAdd").click(function () {
            // 收集表单数据
            var formData = {
                buildingId: $("#addBuildingId").val(),
                roomNumber: $("#addRoomNumber").val(),
                floor: $("#addFloor").val(),
                capacity: $("#addCapacity").val()
            };

            // 验证表单数据
            if (!formData.buildingId || !formData.roomNumber || !formData.floor || !formData.capacity) {
                alert("请填写完整的房间信息");
                return;
            }

            // 发送AJAX请求
            $.ajax({
                url: "<%=request.getContextPath()%>/DormroomsController",
                type: "POST",
                data: {
                    op: "add2",
                    buildingId: formData.buildingId,
                    roomNumber: formData.roomNumber,
                    floor: formData.floor,
                    capacity: formData.capacity
                },
                success: function (response) {
                    alert(response);
                    // 关闭模态框
                    $('#addModal').modal('hide');
                    // 刷新数据
                    show();
                },
                error: function () {
                    alert("添加失败，请稍后再试");
                }
            });
        });

        // 模态框关闭时清空表单
        $('#addModal').on('hidden.bs.modal', function () {
            $(this).find('form')[0].reset();
        });
    });

    // 修改宿舍房间功能
    $(document).ready(function () {
        // 使用事件委托绑定修改按钮点击事件
        $(document).on('click', '.edit-btn', function () {
            // 获取数据属性
            var id = $(this).data('id');
            var buildingId = $(this).data('building-id');
            var number = $(this).data('number');
            var floor = $(this).data('floor');
            var capacity = $(this).data('capacity');

            // 填充表单
            $("#editRoomId").val(id);
            $("#editBuildingId").val(buildingId);
            $("#editRoomNumber").val(number);
            $("#editFloor").val(floor);
            $("#editCapacity").val(capacity);

            // 显示模态框
            $('#editModal').modal('show');
        });

        // 确认修改按钮点击事件
        $("#confirmEdit").click(function () {
            // 收集表单数据
            var formData = {
                roomId: $("#editRoomId").val(),
                buildingId: $("#editBuildingId").val(),
                roomNumber: $("#editRoomNumber").val(),
                floor: $("#editFloor").val(),
                capacity: $("#editCapacity").val()
            };

            // 验证表单数据
            if ( !formData.buildingId || !formData.roomNumber || !formData.floor || !formData.capacity) {
                alert("请填写完整的房间信息");
                return;
            }

            // 发送AJAX请求
            $.ajax({
                url: "<%=request.getContextPath()%>/DormroomsController",
                type: "POST",
                data: {
                    op: "update2",
                    roomId: formData.roomId,
                    buildingId: formData.buildingId,
                    roomNumber: formData.roomNumber,
                    floor: formData.floor,
                    capacity: formData.capacity
                },
                success: function (response) {
                    alert(response);
                    // 关闭模态框
                    $('#editModal').modal('hide');
                    // 重新加载数据
                    show();
                },
                error: function () {
                    alert("修改失败，请稍后再试");
                }
            });
        });

        // 模态框关闭时清空表单
        $('#editModal').on('hidden.bs.modal', function () {
            $(this).find('form')[0].reset();
        });
    });

    // 导出Excel功能
    function exportToExcel() {
        try {
            // 获取表格
            var table = document.getElementById("tableId");
            if (!table) {
                throw new Error("未找到表格元素");
            }
            // 检查是否有数据
            var rows = table.querySelectorAll("tbody tr");
            if (rows.length === 0) {
                alert("没有数据可导出");
                return;
            }
            // 创建工作簿和工作表
            var wb = XLSX.utils.book_new();
            var ws = XLSX.utils.table_to_sheet(table);

            // 设置列宽
            var cols = [];
            var headerCells = table.querySelectorAll("thead th");
            headerCells.forEach(function(header) {
                var maxLength = header.innerText.length;
                rows.forEach(function(row) {
                    var cell = row.querySelector("td:nth-child(" + (cols.length + 1) + ")");
                    if (cell) {
                        maxLength = Math.max(maxLength, cell.innerText.length);
                    }
                });
                cols.push({wch: Math.min(maxLength + 2, 50)}); // 限制最大宽度
            });
            ws['!cols'] = cols;

            // 添加工作表到工作簿
            XLSX.utils.book_append_sheet(wb, ws, "宿舍房间信息");

            // 生成文件名
            var date = new Date();
            var fileName = "宿舍房间信息_" +
                date.getFullYear() +
                (date.getMonth() + 1).toString().padStart(2, '0') +
                date.getDate().toString().padStart(2, '0') +
                ".xlsx";

            // 导出文件
            XLSX.writeFile(wb, fileName);
        } catch (error) {
            console.error("导出Excel时发生错误:", error);
            alert("导出失败：" + error.message);
        }
    }
</script>
</body>
</html>
